// components/search/search.js
import { KeywordModel } from '../../models/keyword.js'
import { BookModel } from '../../models/book.js'
import { paginationBeh } from '../behaviors/pagination.js'
const keywordModel = new KeywordModel()
const bookModel = new BookModel()

Component({
  /**
   * 组件的属性列表
   */
  behaviors: [paginationBeh],
  properties: {
    more: {
      type: String,
      observer: 'loadMore'
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    historyWords: [],
    hotWords: [],
    searching: false,
    searchValue: '',
    loading: false,
    loadingCenter: false,
  },

  /**
   * 组件的方法列表
   */
  attached() {
    this.setData({
      historyWords: keywordModel.getHistory()
    })
    keywordModel.getHot().then(res => this.setData({
      hotWords: res.hot
    })
    )
  },
  methods: {
    onCancel() {
      this.initialize()
      this.triggerEvent('cancel', {}, {})
    },
    onConfirm(event) {
      const word = event.detail.value || event.detail.text
      this.setData({
        searchValue: word
      })
      // 展示搜索内容
      this.setData({
        searching: true
      })
      this._showLoadingCenter()
      bookModel.search(0, word).then(res => {
        this.setMoreData(res.books)
        this.setTotal(res.total)
        this._hideLoadingCenter()
        keywordModel.addToHistory(word)
      })
    },
    clearSearch() {
      this.initialize()
      // 关闭搜索内容
      this.setData({
        searching: false,
        searchValue: ''
      })
    },
    loadMore() {
      const length = this.getCurrentStart()
      const q = this.data.searchValue
      // 当搜索不为空且不在请求中且还有更多数据时，才发送请求
      if (q && !this.data.loading && this.hasMore()) {
        // 加锁
        this.locked()
        bookModel.search(length, q).then(res => {
          this.setMoreData(res.books)
          // 解锁
          this.unLocked()
        }, () => this.unLocked())
      }
    },
    _showLoadingCenter() {
      this.setData({
        loadingCenter: true
      })
    },
    _hideLoadingCenter() {
      this.setData({
        loadingCenter: false
      })
    }
  }
})
